﻿/*
 DotNetNuke - http://www.dotnetnuke.com
 Copyright (c) 2002-2010 by DotNetNuke Corp.

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
 the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
 to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial portions 
 of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
 CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 DEALINGS IN THE SOFTWARE.

*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Hosting;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Data;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Modules.UserDefinedTable.Security;
using DotNetNuke.Security;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.FileSystem;
using DotNetNuke.Services.Localization;
using DotNetNuke.Services.Mail;
using DotNetNuke.UI.Modules;
using DotNetNuke.UI.Skins;
using DotNetNuke.UI.Skins.Controls;
using DotNetNuke.UI.UserControls;
using DotNetNuke.UI.Utilities;
using DotNetNuke.UI.WebControls;

namespace DotNetNuke.Modules.UserDefinedTable
{


  public partial class Configuration : ModuleUserControlBase, IActionable, IPostBackEventHandler
  {

    private ModuleController _objModules;
    protected int RowCount;
    private const string STR_AUTO = "[AUTO]";
    private UserDefinedTableController _udtController;




    public Configuration()
    {
      //base.Init += new EventHandler(this.Page_Init);
      //base.Load += new EventHandler(this.Page_Load);
    }



    protected override void OnInit(EventArgs e)
    {
      base.OnInit(e);

      //base.Init += new EventHandler(this.Page_Init);
      //base.Load += new EventHandler(this.Page_Load);

      ModuleInstanceContext moduleContext = this.ModuleContext;
      this.teSubmissionSuccess.Text = Utilities.CStrN(moduleContext.Settings[SettingName.SubmissionText], DotNetNuke.Services.Localization.Localization.GetString("SubmissionSuccess", this.LocalResourceFile));
      this.teTrackingMessage.Text = Utilities.CStrN(moduleContext.Settings[SettingName.TrackingMessage], "");
      moduleContext = null;

      //hookup posdtback events
      cmdAddField.Click += new EventHandler(cmdAddField_Click);
      cmdCancel.Click += new EventHandler(cmdCancel_Click);
      cmdUpdate.Click += new EventHandler(cmdUpdate_Click);
      cmdEditEmail.Click += new EventHandler(cmdEditEmail_Click);

      cmdEditXSL.Click += new EventHandler(cmdEditXSL_Click);
      cmdGenerateEmail.Click += new EventHandler(cmdGenerateEmail_Click);
      cmdGenerateXSL.Click += new EventHandler(cmdGenerateXSL_Click);

      grdFields.UpdateCommand += new DataGridCommandEventHandler(grdFields_UpdateCommand);
      grdFields.CancelCommand += new DataGridCommandEventHandler(grdFields_CancelCommand);
      grdFields.EditCommand += new DataGridCommandEventHandler(grdFields_EditCommand);
      grdFields.DeleteCommand += new DataGridCommandEventHandler(grdFields_DeleteCommand);
      grdFields.ItemCommand += new DataGridCommandEventHandler(grdFields_ItemCommand);
      grdFields.ItemCreated += new DataGridItemEventHandler(grdFields_ItemCreated);
      grdFields.ItemDataBound += new DataGridItemEventHandler(grdFields_ItemDataBound);

    }




    //private void Page_Init(object sender, EventArgs evt)
    //{
    //  ModuleInstanceContext moduleContext = this.ModuleContext;
    //  this.teSubmissionSuccess.Text = Utilities.CStrN(moduleContext.Settings[SettingName.SubmissionText], DotNetNuke.Services.Localization.Localization.GetString("SubmissionSuccess", this.LocalResourceFile));
    //  this.teTrackingMessage.Text = Utilities.CStrN(moduleContext.Settings[SettingName.TrackingMessage], "");
    //  moduleContext = null;
    //}




    //protected void Page_Load(object sender, EventArgs evt)
    protected override void OnLoad(EventArgs evt)
    {
      base.OnLoad(evt);

      try
      {
        if (!this.Page.IsPostBack)
        {
          DataGrid grdFields = this.grdFields;
          DotNetNuke.Services.Localization.Localization.LocalizeDataGrid(ref grdFields, this.LocalResourceFile);
          this.grdFields = grdFields;
          this.BindData();
        }
        else
        {
          DataRowView dr = this.UdtController.GetFieldsTable().DefaultView[this.CurrentRow];
          dr.BeginEdit();
          dr[FieldsTableColumn.Type] = this.CurrentType;
          dr[FieldsTableColumn.Title] = this.CurrentTitle;
          dr.EndEdit();
          if (this.panFieldSettings.Visible)
            this.AdjustFieldSettings(dr);

        }
        this.SetHelpLinks();
        this.ApplySettingsVisibility();
      }
      catch (Exception e)
      {
        Exception exc = e;
        DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
      }
    }






    private void AdjustFieldSettings(DataRowView dr)
    {
      this.panFieldSettings.Visible = true;
      this.hlpToken.Visible = true;
      this.hlpColumns.Visible = true;

      this.lblField.Text = Utilities.CStrN(dr[FieldsTableColumn.Title], "");
      DataType type = DataType.ByName(Utilities.CStrN(dr[FieldsTableColumn.Type], ""));

      if (type.SupportsDefaultValue)
      {
        this.panDefault.Visible = true;
        this.lblDefault.Text = Utilities.CStrN(type.GetLocalization("DefaultValue"), this.lblDefault.Text);
        this.lblDefault.HelpText = Utilities.CStrN(type.GetLocalization("DefaultValue.Help"), this.lblDefault.HelpText);
      }
      else
        this.panDefault.Visible = false;

      if (type.SupportsInputSettings)
      {
        this.panInputSettings.Visible = true;
        IDictionary inputSettingsList = type.InputSettingsList;
        if (inputSettingsList == null)
        {
          this.txtInputSettings.Visible = true;
          this.cboInputSettings.Visible = false;
        }
        else
        {
          this.cboInputSettings.DataSource = inputSettingsList;
          string selectedValue = this.cboInputSettings.SelectedValue;
          this.cboInputSettings.DataBind();

          if ((selectedValue != "") && (this.cboInputSettings.Items.FindByValue(selectedValue) != null))
            this.cboInputSettings.SelectedValue = selectedValue;

          else
            this.cboInputSettings.SelectedValue = type.InputSettingDefault;

          this.txtInputSettings.Visible = false;
          this.cboInputSettings.Visible = true;
        }
        this.lblInputSettings.Text = Utilities.CStrN(type.GetLocalization("InputSetting"), this.lblInputSettings.Text);
        this.lblInputSettings.HelpText = Utilities.CStrN(type.GetLocalization("InputSetting.Help"), this.lblInputSettings.HelpText);
        this.rblListType.Visible = type.InputSettingsIsValueList;
      }
      else
        this.panInputSettings.Visible = false;

      if (type.SupportsOutputSettings)
      {
        this.panOutputSettings.Visible = true;
        this.lblOutputSettings.Text = Utilities.CStrN(type.GetLocalization("OutputSetting"), this.lblOutputSettings.Text);
        this.lblOutputSettings.HelpText = Utilities.CStrN(type.GetLocalization("OutputSetting.Help"), this.lblOutputSettings.HelpText);
      }
      else
        this.panOutputSettings.Visible = false;

      if (type.SupportsNormalizeFlag)
      {
        this.panNormalizeFlag.Visible = true;
        this.lblNormalizeFlag.Text = Utilities.CStrN(type.GetLocalization("NormalizeFlag"), this.lblNormalizeFlag.Text);
        this.lblNormalizeFlag.HelpText = Utilities.CStrN(type.GetLocalization("NormalizeFlag.Help"), this.lblNormalizeFlag.HelpText);
      }
      else
        this.panNormalizeFlag.Visible = false;

      this.panShowOnEdit.Visible = type.SupportsHideOnEdit;
      this.panEditStyle.Visible = type.SupportsEditStyle;
      this.panValidationRule.Visible = type.SupportsValidation;
      this.panValidationMessage.Visible = type.SupportsValidation;
      this.panHelpText.Visible = type.SupportsEditing;
      this.panFieldSettings.Visible = ((this.panDefault.Visible || this.panInputSettings.Visible) || (this.panOutputSettings.Visible || this.panValidationMessage.Visible)) || ((this.panNormalizeFlag.Visible || this.panShowOnEdit.Visible) || this.panHelpText.Visible);
      this.hlpColumns.Visible = this.panFieldSettings.Visible;
      this.hlpToken.Visible = this.panFieldSettings.Visible;
    }





    private void ApplySettingsVisibility()
    {
      bool flag = this.rblUsageListForm.SelectedValue == "Form";
      this.dshRendering.Visible = true;
      this.liRememberSettings.Visible = this.rblUsageListForm.SelectedValue.Contains("Form");
      this.FindControl(this.dshRendering.Section).Visible = true;
      this.dshFormsSettings.Visible = flag;
      this.teSubmissionSuccess.Visible = flag;
      this.FindControl(this.dshFormsSettings.Section).Visible = flag;
      this.rowOnSubmissionRedirect.Visible = this.rblOnSubmission.SelectedValue == "Redirect";
      this.rowSubmissionText.Visible = !this.rowOnSubmissionRedirect.Visible;
      this.rowListViewPermission.Visible = this.rblUsageListForm.SelectedValue.Contains("Form");
      this.dshChangeTracking.Visible = this.chkTracking.Checked;
      this.teTrackingMessage.Visible = this.chkTracking.Checked;
      this.FindControl(this.dshChangeTracking.Section).Visible = this.chkTracking.Checked;
      this.rowTrackingScript.Visible = this.rblBodyType.SelectedValue == "XslScript";
      string selectedValue = this.renderMethodRadioButtonList.SelectedValue;
      if (selectedValue == RenderingMethod.GridRendering)
      {
        this.rowUserDefined.Visible = false;
        this.rowPreDefined.Visible = false;
        this.rowDataGrid.Visible = true;
      }
      else if (selectedValue == RenderingMethod.PredefinedXSL)
      {
        this.rowUserDefined.Visible = false;
        this.rowPreDefined.Visible = true;
        this.rowDataGrid.Visible = false;
      }
      else if (selectedValue == RenderingMethod.UserdefinedXSL)
      {
        this.rowUserDefined.Visible = true;
        this.rowPreDefined.Visible = false;
        this.rowDataGrid.Visible = false;
      }
      this.HyperLinkStyleSheet.NavigateUrl = string.Format("{0}/{1}/{2}", this.TemplateSourceDirectory, Definition.XSLFolderName, this.XslPreDefinedDropDownList.SelectedValue);
    }




    private void BindData()
    {
      this.BindData(false);
    }




    private void BindData(bool blnInsertField)
    {
      this.BindFields(blnInsertField);
      this.BindSettings();
    }




    private void BindFields()
    {
      this.BindFields(false);
    }




    private void BindFields(bool blnInsertField)
    {

      DataTable fieldsTable = this.UdtController.GetFieldsTable(blnInsertField);
      this.RowCount = fieldsTable.Rows.Count;

      if (blnInsertField)
        for (int i = this.RowCount - 1; i >= 0; i += -1)
          if (fieldsTable.Rows[i]["UserDefinedFieldId"].ToString() == "-1")
          {
            this.grdFields.EditItemIndex = i;
            this.AdjustFieldSettings(fieldsTable.DefaultView[i]);
            break;
          }

      this.panFieldSettings.Visible = false;
      this.hlpColumns.Visible = false;
      this.hlpToken.Visible = false;

      this.grdFields.DataSource = fieldsTable.DefaultView;
      this.grdFields.DataBind();
      this.grdFields.Visible = this.RowCount != 0;

      this.cboSortField.DataSource = new DataView(fieldsTable, "UserDefinedFieldId<>'-1'", string.Empty, DataViewRowState.CurrentRows);
      this.cboSortField.DataBind();
      this.cboSortField.Items.Insert(0, new ListItem(DotNetNuke.Services.Localization.Localization.GetString("Not_Specified"), string.Empty));

      string selectedValue = this.cboSortField.SelectedValue;

      if (this.cboSortField.Items.FindByValue(selectedValue) != null)
        this.cboSortField.Items.FindByValue(selectedValue).Selected = true;

    }




    private void BindFieldSettings(DataRowView dr)
    {
      this.txtHelpText.Text = Utilities.CStrN(dr[FieldsTableColumn.HelpText], "");
      this.txtDefault.Text = Utilities.CStrN(dr[FieldsTableColumn.Default], "");
      string input = Utilities.CStrN(dr[FieldsTableColumn.InputSettings], "");

      if (input.EndsWith(Definition.verticalRadioButtonEnabledToken))
        this.rblListType.SelectedValue = "RadioButtons";

      else if (input.EndsWith(Definition.horizontalRadioButtonEnabledToken))
        this.rblListType.SelectedValue = "RadioButtonsHorizontal";

      this.txtInputSettings.Text = Regex.Replace(input, @"-\[\[(?:h|v)RBL]]$", "");
      this.txtOutputSettings.Text = Utilities.CStrN(dr[FieldsTableColumn.OutputSettings], "");
      this.chkNormalizeFlag.Checked = Utilities.CBoolN(dr[FieldsTableColumn.NormalizeFlag], false);
      this.chkShowOnEdit.Checked = Utilities.CBoolN(dr[FieldsTableColumn.ShowOnEdit], false);
      this.txtValidationRule.Text = Utilities.CStrN(dr[FieldsTableColumn.ValidationRule], "");
      this.txtValidationMessage.Text = Utilities.CStrN(dr[FieldsTableColumn.ValidationMessage], "");

      if (this.cboInputSettings.Visible)
        this.cboInputSettings.SelectedValue = Utilities.CStrN(input, "String");

    }





    private void BindSettings()
    {
      ModuleInstanceContext moduleContext = this.ModuleContext;
      this.chkExcludeFromSearch.Checked = Utilities.CBoolN((moduleContext.Settings[SettingName.ExcludeFromSearch]), false);
      this.chkCalculatedColumnInForm.Checked = Utilities.CBoolN((moduleContext.Settings[SettingName.CalculatedColumnsRenderExpressionInForm]), false);
      this.cboSortField.ClearSelection();

      if (this.cboSortField.Items.FindByValue((string)moduleContext.Settings[SettingName.SortField]) != null)
        this.cboSortField.Items.FindByValue((string)moduleContext.Settings[SettingName.SortField]).Selected = true;
      
      this.cboSortOrder.ClearSelection();

      if (this.cboSortOrder.Items.FindByValue((string)moduleContext.Settings[SettingName.SortOrder]) != null)
        this.cboSortOrder.Items.FindByValue((string)moduleContext.Settings[SettingName.SortOrder]).Selected = true;
      
      this.chkURLNewWindow.Checked = Utilities.CBoolN((moduleContext.Settings[SettingName.URLNewWindow]), false);

      //updated by asida@centrum.cz
      loadFolders();
      try
      {
        cboDefaultFolder.SelectedValue = Utilities.CStrN((moduleContext.Settings[SettingName.DocDataFolder]),"");
      }
      catch( Exception exc)
      {
        // suppress exception.  Can be caused if the selected folder has been deleted
      }

      this.chkForceDownload.Checked = Utilities.CBoolN((moduleContext.Settings[SettingName.ForceDownload]), false);
      this.chkUserLinkNewWindow.Checked = Utilities.CBoolN((moduleContext.Settings[SettingName.UserLinkNewWindow]), false);
      this.rblUrlOptimization.SelectedValue = Utilities.CBoolN((moduleContext.Settings[SettingName.URLDownloadTracking]), false).ToString();
      this.rblUserLinkCaption.SelectedValue = Utilities.CStrN((moduleContext.Settings[SettingName.UserLinkCaption]), "DisplayName");
      this.chkCnCLink.Checked = Utilities.CBoolN((moduleContext.Settings[SettingName.CnCLink]), false);
      this.txtImageWidth.Text = Utilities.CStrN((moduleContext.Settings[SettingName.ImageWidth]), "");
      this.txtImageHeight.Text = Utilities.CStrN((moduleContext.Settings[SettingName.ImageHeight]), "");
      this.txtFilter.Text = Utilities.CStrN((moduleContext.Settings[SettingName.Filter]), "");
      this.txtTopCount.Text = Utilities.CStrN((moduleContext.Settings[SettingName.TopCount]), "");
      this.chkShowSearchTextBox.Checked = Utilities.CBoolN((moduleContext.Settings[SettingName.ShowSearchTextBox]), false);
      this.chkShowNoRecordsUntilSearch.Checked = Utilities.CBoolN((moduleContext.Settings[SettingName.ShowNoRecordsUntilSearch]), false);
      this.chkSimpleSearch.Checked = Utilities.CBoolN((moduleContext.Settings[SettingName.SimpleSearch]), false);
      this.chkURLSearch.Checked = Utilities.CBoolN((moduleContext.Settings[SettingName.URLSearch]), false);
      
      if (Utilities.CBoolN((moduleContext.Settings[SettingName.ControlFullWidth]), false))
        this.rblControlWidth.SelectedValue = "FullWidth";

      else
        this.rblControlWidth.SelectedValue = "ClassicWidth";
      
      this.cboDnnCssClasses.ClearSelection();
      if (this.cboDnnCssClasses.Items.FindByValue(Utilities.CStrN((moduleContext.Settings[SettingName.UsedCssClasses]), "")) != null)
        this.cboDnnCssClasses.Items.FindByValue(Utilities.CStrN((moduleContext.Settings[SettingName.UsedCssClasses]), "")).Selected = true;
      
      this.cboPaging.ClearSelection();
      if (moduleContext.Settings.ContainsKey(SettingName.Paging) && (this.cboPaging.Items.FindByValue((string)moduleContext.Settings[SettingName.Paging])) != null)
        this.cboPaging.SelectedValue = (string)moduleContext.Settings[SettingName.Paging];
      
      string gridRendering = (string)moduleContext.Settings[SettingName.RenderingMethod];

      if ( string.IsNullOrEmpty(gridRendering) )
        gridRendering = RenderingMethod.GridRendering;
      
      this.renderMethodRadioButtonList.SelectedValue = gridRendering;
      this.XslPreDefinedDropDownList.Items.Clear();

      foreach (string str3 in Directory.GetFiles(HostingEnvironment.MapPath(string.Format("{0}/XslStyleSheets", this.TemplateSourceDirectory)), "*.xsl?"))
        this.XslPreDefinedDropDownList.Items.Add(new System.IO.FileInfo(str3).Name);

      try
      {

        if (moduleContext.Settings.ContainsKey(SettingName.XslPreDefinedStyleSheet))
          this.XslPreDefinedDropDownList.SelectedValue = ((string)moduleContext.Settings[SettingName.XslPreDefinedStyleSheet]).Substring("~/DesktopModules/UserDefinedTable/XslStyleSheets/".Length);

      }
      catch (Exception e)
      {
        Exception exception = e; 
      }
      try
      {
        if (moduleContext.Settings.ContainsKey(SettingName.XslUserDefinedStyleSheet))
          this.XslUserDefinedUrlControl.Url = (string)moduleContext.Settings[SettingName.XslUserDefinedStyleSheet];
        
      }
      catch (Exception exception4)
      {
        Exception exception2 = exception4; 
      }

      this.dshRendering.IsExpanded = (gridRendering != RenderingMethod.GridRendering) | (this.cboSortField.SelectedIndex != 0);
      this.rblUsageListForm.SelectedValue = Utilities.CStrN((moduleContext.Settings[SettingName.ListOrForm]), "List");
      this.chkListViewPermission.Checked = Utilities.CBoolN((moduleContext.Settings[SettingName.ShowListRequiresPermission]), false);
      this.rblTableFreeForm.SelectedValue = Utilities.CBoolN((moduleContext.Settings[SettingName.TableFreeEditForm]), false).ToString();
      this.chkTracking.Checked = Utilities.CBoolN((moduleContext.Settings[SettingName.TrackingEnabled]), false);
      this.chkTrackingOnDelete.Checked = Utilities.CBoolN((moduleContext.Settings[SettingName.TrackingTriggerOnDelete]), false);
      this.chkTrackingOnNew.Checked = Utilities.CBoolN((moduleContext.Settings[SettingName.TrackingTriggerOnNew]), true);
      this.chkTrackingOnUpdate.Checked = Utilities.CBoolN((moduleContext.Settings[SettingName.TrackingTriggerOnUpdate]), false);
      this.txtOnNew.Text = Utilities.CStrN((moduleContext.Settings[SettingName.TrackingTextOnNew]), "");
      this.txtOnUpdate.Text = Utilities.CStrN((moduleContext.Settings[SettingName.TrackingTextOnUpdate]), "");
      this.txtOnDelete.Text = Utilities.CStrN((moduleContext.Settings[SettingName.TrackingTextOnDelete]), "");
      this.txtTrackingEmailAddresses.Text = Utilities.CStrN((moduleContext.Settings[SettingName.TrackingEmailTo]), "");
      this.txtTrackingEmail_CC.Text = Utilities.CStrN((moduleContext.Settings[SettingName.TrackingEmailCc]), "");
      this.txtTrackingEmail_BCC.Text = Utilities.CStrN((moduleContext.Settings[SettingName.TrackingEmailBcc]), "");
      this.txtTrackingEmail_from.Text = Utilities.CStrN((moduleContext.Settings[SettingName.TrackingEmailFrom]), "");
      this.txtTrackingEmail_replyto.Text = Utilities.CStrN((moduleContext.Settings[SettingName.TrackingEmailReplyTo]), "");
      this.txtTrackingSubject.Text = Utilities.CStrN((moduleContext.Settings[SettingName.TrackingSubject]), "");
      string str2 = Utilities.CStrN((moduleContext.Settings[SettingName.TrackingScript]), "[AUTO]");

      if (str2 == "[AUTO]")
        this.rblBodyType.SelectedValue = "Auto";

      else
      {
        this.rblBodyType.SelectedValue = "XslScript";
        try
        {
          this.XslTracking.Url = str2;
        }
        catch (Exception exception5)
        {
          Exception exception3 = exception5; 
        }
      }

      this.rblFormLinksOrButtons.SelectedValue = Utilities.CBoolN((moduleContext.Settings[SettingName.UseButtons]), false).ToString();
      this.rblOnSubmission.SelectedValue = Utilities.CStrN((moduleContext.Settings[SettingName.UponSubmitAction]), "Form");
      this.urlOnSubmissionRedirect.Url = Utilities.CStrN((moduleContext.Settings[SettingName.UponSubmitRedirect]), "");
      moduleContext = null;
    }





    private void cmdAddField_Click(object sender, EventArgs evt)
    {
      try
      {
        this.SaveSettings((sender));
        this.grdFields.EditItemIndex = -1;
        this.BindFields(true);
        this.CurrentType = "String";
        this.CurrentTitle = "";
      }
      catch (Exception e)
      {
        Exception exc = e;
        DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
      }
    }





    private void cmdCancel_Click(object sender, EventArgs evt)
    {
      this.Response.Redirect(DotNetNuke.Common.Globals.NavigateURL(this.ModuleContext.TabId), true);
    }





    protected void cmdEditEmail_Click(object sender, EventArgs evt)
    {
      int editableFileId = this.GetEditableFileId(this.XslTracking.Url.ToLowerInvariant());

      if (editableFileId > -1)
      {
        this.SaveSettings((sender));
        this.Response.Redirect(this.ModuleContext.EditUrl("FileID", editableFileId.ToString(), "GenerateXsl"), true);
      }
    }






    private void cmdEditXSL_Click(object sender, EventArgs evt)
    {
      int editableFileId = this.GetEditableFileId(this.XslUserDefinedUrlControl.Url.ToLowerInvariant());

      if (editableFileId > -1)
      {
        this.SaveSettings((sender));
        this.Response.Redirect(this.ModuleContext.EditUrl("FileID", editableFileId.ToString(), "GenerateXsl"), true);
      }
    }





    protected void cmdGenerateEmail_Click(object sender, EventArgs evt)
    {
      this.SaveSettings((sender));
      this.Response.Redirect(this.ModuleContext.EditUrl("tracking", "true", "GenerateXsl"), true);
    }





    private void cmdGenerateXSL_Click(object sender, EventArgs evt)
    {
      this.SaveSettings((sender));
      this.Response.Redirect(this.ModuleContext.EditUrl("GenerateXsl"), true);
    }





    private void cmdUpdate_Click(object sender, EventArgs evt)
    {
      if (this.ValidateMailTo())
      {
        if (this.chkExcludeFromSearch.Checked)
          DotNetNuke.Data.DataProvider.Instance().DeleteSearchItems(this.ModuleContext.ModuleId);

        this.SaveSettings((sender));
        this.Response.Redirect(DotNetNuke.Common.Globals.NavigateURL(this.ModuleContext.TabId), true);
      }
    }





    private int GetEditableFileId(string url)
    {
      if (url.StartsWith("fileid=*", StringComparison.OrdinalIgnoreCase))
      {
        int fileId = int.Parse(UrlUtils.GetParameterValue(url));
        FileController controller = new FileController();

        if (Utilities.hasWritePermission(controller.GetFileById(fileId, this.ModuleContext.PortalId).Folder, this.ModuleContext.PortalId))
          return fileId;

      }
      return -1;
    }





    private void grdFields_CancelCommand(object source, DataGridCommandEventArgs evt)
    {
      try
      {
        this.grdFields.EditItemIndex = -1;
        this.SaveSettings((source));
        this.BindFields();
      }
      catch (Exception e)
      {
        Exception exc = e;
        DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
      }
    }




    private void grdFields_DeleteCommand(object source, DataGridCommandEventArgs evt)
    {
      try
      {
        this.SaveSettings((source));
        DataTable fieldsTable = this.UdtController.GetFieldsTable(false);
        int num = int.Parse(Convert.ToString((this.grdFields.DataKeys[evt.Item.ItemIndex])));

        if (DataType.ByName(Utilities.CStrN((fieldsTable.Select(string.Format("UserDefinedFieldId={0}", num))[0][FieldsTableColumn.Type]), "")).IsUserDefinedField)
          this.UdtController.DeleteField(num);

        this.grdFields.EditItemIndex = -1;
        this.BindFields();
      }
      catch (Exception e)
      {

        Exception exc = e;
        DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);

      }
    }





    private void grdFields_EditCommand(object source, DataGridCommandEventArgs evt)
    {
      try
      {
        this.SaveSettings((source));
        this.grdFields.EditItemIndex = evt.Item.ItemIndex;
        this.grdFields.SelectedIndex = -1;
        this.BindFields();
        this.CurrentRow = evt.Item.ItemIndex;
        DataRowView view = this.UdtController.GetFieldsTable().DefaultView[this.CurrentRow];
        this.CurrentType = Utilities.CStrN((view[FieldsTableColumn.Type]), "");
        this.CurrentTitle = Utilities.CStrN((view[FieldsTableColumn.Title]), "");
      }
      catch (Exception e)
      {

        Exception exc = e;
        DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);

      }
    }




    private void grdFields_ItemCommand(object source, DataGridCommandEventArgs evt)
    {
      string str = evt.CommandName.ToLowerInvariant();
      if (((str != "edit") && (str != "delete")) && ((str != "update") && (str != "cancel")))
      {
        if (str == "fieldtypechanged")
        {
          bool addNewColumn = int.Parse(Convert.ToString((this.grdFields.DataKeys[evt.Item.ItemIndex]))) == -1;
          DataRowView dr = this.UdtController.GetFieldsTable(addNewColumn).DefaultView[evt.Item.DataSetIndex];
          DropDownList list = (DropDownList)evt.Item.FindControl("cboFieldType");
          dr.BeginEdit();
          dr[FieldsTableColumn.Type] = list.SelectedValue;
          this.AdjustFieldSettings(dr);
          this.CurrentType = Utilities.CStrN((dr[FieldsTableColumn.Type]), "");
        }
        else
          this.grdFields_Move((source), evt);

      }
    }




    private void grdFields_ItemCreated(object sender, DataGridItemEventArgs evt)
    {
      try
      {
        Control control = evt.Item.FindControl("cmdDeleteUserDefinedField");
        if (control != null)
        {
          ClientAPI.AddButtonConfirm((WebControl)control, DotNetNuke.Services.Localization.Localization.GetString("DeleteField", this.LocalResourceFile));
        }
        if (evt.Item.ItemType == ListItemType.Header)
        {
          evt.Item.Cells[1].Attributes.Add("scope", "col");
          evt.Item.Cells[2].Attributes.Add("scope", "col");
          evt.Item.Cells[3].Attributes.Add("scope", "col");
        }
      }
      catch (Exception e)
      {

        Exception exc = e;
        DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);

      }
    }





    private void grdFields_ItemDataBound(object sender, DataGridItemEventArgs evt)
    {
      try
      {
        if (evt.Item.ItemType == ListItemType.EditItem)
        {
          CheckBox box3 = (CheckBox)evt.Item.FindControl("chkVisible");
          Label label5 = (Label)evt.Item.FindControl("lblVisible");
          label5.Text = string.Format("<label style=\"display:none;\" for=\"{0}\">{1}</label>", box3.ClientID, DotNetNuke.Services.Localization.Localization.GetString("Visible.Header", this.LocalResourceFile));
          CheckBox box = (CheckBox)evt.Item.FindControl("chkRequired");
          Label label3 = (Label)evt.Item.FindControl("lblRequired");
          label3.Text = string.Format("<label style=\"display:none;\" for=\"{0}\">{1}</label>", box.ClientID, DotNetNuke.Services.Localization.Localization.GetString("Required.Header", this.LocalResourceFile));
          CheckBox box2 = (CheckBox)evt.Item.FindControl("chkSearchable");
          Label label4 = (Label)evt.Item.FindControl("lblSearchable");
          label4.Text = string.Format("<label style=\"display:none;\" for=\"{0}\">{1}</label>", box3.ClientID, DotNetNuke.Services.Localization.Localization.GetString("Searchable.Header", this.LocalResourceFile));
          TextBox box4 = (TextBox)evt.Item.FindControl("txtFieldTitle");
          Label label = (Label)evt.Item.FindControl("lblFieldTitle");
          label.Text = string.Format("<label style=\"display:none;\" for=\"{0}\">{1}</label>", box4.ClientID, DotNetNuke.Services.Localization.Localization.GetString("Title.Header", this.LocalResourceFile));
          DropDownList list = (DropDownList)evt.Item.FindControl("cboFieldType");
          Label label2 = (Label)evt.Item.FindControl("lblFieldType");
          LinkButton button = (LinkButton)evt.Item.FindControl("cmdChangeFieldType");
          label2.Text = string.Format("<label style=\"display:none;\" for=\"{0}\">{1}</label>", list.ClientID, DotNetNuke.Services.Localization.Localization.GetString("Type.Header", this.LocalResourceFile));
          list.Attributes["onChange"] = "location.href=document.getElementById('" + button.ClientID + "').href;";
          this.AdjustFieldSettings((DataRowView)evt.Item.DataItem);
          this.BindFieldSettings((DataRowView)evt.Item.DataItem);
        }
      }
      catch (Exception e)
      {

        Exception exc = e;
        DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);

      }
    }





    public void grdFields_Move(object source, DataGridCommandEventArgs evt)
    {
      try
      {
        this.SaveSettings((source));
        switch (evt.CommandArgument.ToString())
        {
          case "Up":
            this.UdtController.SwapFieldOrder((int)this.grdFields.DataKeys[evt.Item.ItemIndex - 1], (int)this.grdFields.DataKeys[evt.Item.ItemIndex]);
            this.BindFields();
            break;

          case "Down":
            this.UdtController.SwapFieldOrder((int)this.grdFields.DataKeys[evt.Item.ItemIndex + 1], (int)this.grdFields.DataKeys[evt.Item.ItemIndex]);
            this.BindFields();
            break;
        }
      }
      catch (Exception e)
      {

        Exception exc = e;
        DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);

      }
    }





    private void grdFields_UpdateCommand(object source, DataGridCommandEventArgs evt)
    {
      try
      {
        CheckBox box3 = (CheckBox)evt.Item.FindControl("chkVisible");
        CheckBox box2 = (CheckBox)evt.Item.FindControl("chkSearchable");
        CheckBox box = (CheckBox)evt.Item.FindControl("chkIsPrivate");
        string dataTypeName = ((HtmlInputHidden)evt.Item.FindControl("hiddenOldFieldType")).Value;
        string oldfieldtitle = ((HtmlInputHidden)evt.Item.FindControl("hiddenOldFieldTitle")).Value;
        string expression = ((HtmlInputHidden)evt.Item.FindControl("hiddenFieldOrder")).Value;

        if (expression == null || (expression == ""))
          expression = Null.NullInteger.ToString();

        TextBox box4 = (TextBox)evt.Item.FindControl("txtFieldTitle");
        DropDownList list = (DropDownList)evt.Item.FindControl("cboFieldType");
        string fieldType = list.SelectedItem.Value;
        string helpText = this.txtHelpText.Text.Trim();
        string userInput = box4.Text.Trim();
        if (!ModuleSecurity.IsAdministrator())
          userInput = new PortalSecurity().InputFilter(userInput, PortalSecurity.FilterFlag.NoScripting);

        string text = this.txtInputSettings.Text;
        if (this.cboInputSettings.Visible)
          text = this.cboInputSettings.SelectedValue;

        if (this.rblListType.SelectedValue == "RadioButtons")
          text = text + Definition.verticalRadioButtonEnabledToken;

        if (this.rblListType.SelectedValue == "RadioButtonsHorizontal")
          text = text + Definition.horizontalRadioButtonEnabledToken;

        if (this.IsAllowedFieldTitle(userInput) && this.isUniqueFieldTitle(userInput, oldfieldtitle))
        {
          if (DataType.ByName(dataTypeName).IsUserDefinedField)
          {
            CheckBox box5 = (CheckBox)evt.Item.FindControl("chkRequired");
            if (int.Parse(Convert.ToString((this.grdFields.DataKeys[evt.Item.ItemIndex]))) == Null.NullInteger)
            {
              int fieldID = this.UdtController.AddField(userInput, int.Parse(expression), helpText, box5.Checked, fieldType, this.txtDefault.Text, box3.Checked, this.chkShowOnEdit.Checked, box2.Checked, box.Checked, text, this.txtOutputSettings.Text, this.chkNormalizeFlag.Checked, this.txtValidationRule.Text, this.txtValidationMessage.Text, this.txtEditStyle.Text);

              if (this.txtDefault.Text != "")
                this.UdtController.FillDefaultData(fieldID, this.txtDefault.Text);

            }
            else
            {
              int fieldId = int.Parse(Convert.ToString((this.grdFields.DataKeys[evt.Item.ItemIndex])));
              this.CheckCast(fieldType, dataTypeName, userInput, fieldId);
              this.UdtController.UpdateField(fieldId, userInput, helpText, box5.Checked, fieldType, this.txtDefault.Text, box3.Checked, this.chkShowOnEdit.Checked, box2.Checked, box.Checked, text, this.txtOutputSettings.Text, this.chkNormalizeFlag.Checked, this.txtValidationRule.Text, this.txtValidationMessage.Text, this.txtEditStyle.Text);
            }
          }
          else
            this.UdtController.UpdateField(int.Parse(Convert.ToString((this.grdFields.DataKeys[evt.Item.ItemIndex]))), userInput, helpText, true, dataTypeName, string.Empty, box3.Checked, this.chkShowOnEdit.Checked, box2.Checked, box.Checked, text, this.txtOutputSettings.Text, this.chkNormalizeFlag.Checked, this.txtValidationRule.Text, this.txtValidationMessage.Text, this.txtEditStyle.Text);

          this.grdFields.EditItemIndex = Null.NullInteger;
          this.BindFields();
        }
      }
      catch (Exception e)
      {
        Exception exc = e;
        DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
      }
    }





    private bool CheckCast(string newFieldType, string oldFieldType, string fieldName, int FieldId)
    {
      if (string.IsNullOrEmpty(oldFieldType))
        return true;

      foreach (string str in DataType.ByName(oldFieldType).SupportedCasts.Split("|".ToCharArray()))
        if (newFieldType == str)
          return true;

      if (!this.UdtController.FieldHasData(FieldId))
        return false;

      string message = string.Format(Utilities.CStrN(DotNetNuke.Services.Localization.Localization.GetString("UnsupportedCast.ErrorMessage", this.LocalResourceFile), "You have changed the fieldtype for {2} from {0} to {1}. Note that this may cause an error"), DataType.ByName(oldFieldType).GetLocalization(""), DataType.ByName(newFieldType).GetLocalization(""), fieldName);
      Skin.AddModuleMessage(this, message, ModuleMessage.ModuleMessageType.YellowWarning);
      return false;
    }

    private void chkShowSearchTextBox_CheckedChanged(object sender, EventArgs evt)
    {
      bool flag = this.chkShowSearchTextBox.Checked;
      this.chkShowNoRecordsUntilSearch.Enabled = flag;
      this.chkSimpleSearch.Enabled = flag;
      this.chkURLSearch.Enabled = flag;
      if (!flag)
      {
        this.chkShowNoRecordsUntilSearch.Checked = false;
        this.chkSimpleSearch.Checked = false;
        this.chkURLSearch.Checked = false;
      }
    }

    private bool IsAllowedFieldTitle(string Title)
    {
      if (Title.IndexOfAny(":,*?".ToCharArray()) > -1)
      {
        Skin.AddModuleMessage(this, DotNetNuke.Services.Localization.Localization.GetString("SpecialCharactersInFieldTitle.ErrorMessage", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
        return false;
      }
      if (Title.IndexOf(DataTableColumn.Appendix_Prefix) > -1)
      {
        Skin.AddModuleMessage(this, DotNetNuke.Services.Localization.Localization.GetString("UDT_InFieldTitle.ErrorMessage", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
        return false;
      }
      return (!string.IsNullOrEmpty(Title));
    }





    private bool isUniqueFieldTitle(string fieldTitle, string oldfieldtitle)
    {
      oldfieldtitle = oldfieldtitle.ToLowerInvariant();
      DataTable fieldsTable = this.UdtController.GetFieldsTable();
      int num = 0;

      foreach (DataRow current in fieldsTable.Rows)
      {
        if (((string)current[FieldsTableColumn.Title]).ToLowerInvariant() == fieldTitle.ToLowerInvariant() && ((string)current[FieldsTableColumn.Title]).ToLowerInvariant() != oldfieldtitle)
          num++;
      }
      if (num > 0)
      {
        Skin.AddModuleMessage(this, DotNetNuke.Services.Localization.Localization.GetString("UniqueFieldName.ErrorMessage", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
        return false;
      }
      return true;
    }





    public void RaisePostBackEvent(string eventArgument)
    {
      switch (eventArgument)
      {
        case "ResetModuleTabSettings":
          this.ModulesController.DeleteTabModuleSettings(this.ModuleContext.TabModuleId);
          break;

        case "SaveSettingsAsDefault":
          {
            this.SaveSettings(this);
            Hashtable tabModuleSettings = this.ModulesController.GetTabModuleSettings(this.ModuleContext.TabModuleId);

            foreach (string settingName in tabModuleSettings.Keys)
              this.ModulesController.UpdateModuleSetting(this.ModuleContext.ModuleId, settingName, (string)tabModuleSettings[settingName]);

            break;
          }
        case "DeleteAll":
          this.UdtController.DeleteRows();
          this.Response.Redirect(DotNetNuke.Common.Globals.NavigateURL(this.ModuleContext.TabId), true);
          break;
      }
    }




    private void SavePendingItem(object sender)
    {
      if (this.grdFields.EditItemIndex > -1)
      {
        DataGridCommandEventArgs e = new DataGridCommandEventArgs(this.grdFields.Items[this.grdFields.EditItemIndex], this.cmdAddField, new CommandEventArgs("Update", null));
        this.grdFields_UpdateCommand((sender), e);
      }
    }




    private void SaveSettings(object sender)
    {

      int num3;

      try
      {
        ModuleController controller = new ModuleController();
        this.UpdateModuleSetting(SettingName.ExcludeFromSearch, this.chkExcludeFromSearch.Checked.ToString());
        this.UpdateModuleSetting(SettingName.CalculatedColumnsRenderExpressionInForm, this.chkCalculatedColumnInForm.Checked.ToString());
        this.UpdateModuleSetting(SettingName.URLNewWindow, this.chkURLNewWindow.Checked.ToString());
        this.UpdateModuleSetting(SettingName.URLDownloadTracking, this.rblUrlOptimization.SelectedValue);
        this.UpdateModuleSetting(SettingName.ForceDownload, this.chkForceDownload.Checked.ToString());

        //asida@centrum.cz default folder
        this.UpdateModuleSetting(SettingName.DocDataFolder, cboDefaultFolder.SelectedValue);

        this.UpdateModuleSetting(SettingName.UserLinkCaption, this.rblUserLinkCaption.SelectedValue);
        this.UpdateModuleSetting(SettingName.UserLinkNewWindow, this.chkUserLinkNewWindow.Checked.ToString());
        this.UpdateModuleSetting(SettingName.CnCLink, this.chkCnCLink.Checked.ToString());

        if (this.cboSortField.SelectedItem != null)
        {
          this.UpdateTabModuleSetting(SettingName.SortField, this.cboSortField.SelectedItem.Value);
          if (this.cboSortField.SelectedIndex == 0)
            this.UpdateTabModuleSetting(SettingName.SortOrder, string.Empty);

          else
            this.UpdateTabModuleSetting(SettingName.SortOrder, Utilities.CStrN(this.cboSortOrder.SelectedItem.Value, "ASC"));

        }
        else
        {
          this.UpdateTabModuleSetting(SettingName.SortField, string.Empty);
          this.UpdateTabModuleSetting(SettingName.SortOrder, string.Empty);
        }
        this.UpdateTabModuleSetting(SettingName.ControlFullWidth, (this.rblControlWidth.SelectedValue == "FullWidth").ToString());
        if (string.IsNullOrEmpty(this.txtImageWidth.Text))
          this.UpdateModuleSetting(SettingName.ImageWidth, string.Empty);

        else
        {
          int num = int.Parse(this.txtImageWidth.Text);

          if (num < 5)
            num = 5;

          if (num > 250)
            num = 250;

          this.UpdateModuleSetting(SettingName.ImageWidth, num.ToString());
        }

        if (string.IsNullOrEmpty(this.txtImageHeight.Text))
          this.UpdateModuleSetting(SettingName.ImageHeight, string.Empty);

        else
        {
          int num2 = int.Parse(this.txtImageHeight.Text);

          if (num2 < 5)
            num2 = 5;

          if (num2 > 250)
            num2 = 250;

          this.UpdateModuleSetting(SettingName.ImageHeight, num2.ToString());
        }
        string selectedValue = this.renderMethodRadioButtonList.SelectedValue;
        string str4 = "";
        string str = "";
        if ((selectedValue == RenderingMethod.UserdefinedXSL) && !string.IsNullOrEmpty(this.XslUserDefinedUrlControl.Url))
        {
          DotNetNuke.Services.FileSystem.FileInfo fileById = new FileController().GetFileById(int.Parse(this.XslUserDefinedUrlControl.Url.Substring(7)), this.ModuleContext.PortalId);
          if (fileById == null)
          {
            selectedValue = RenderingMethod.GridRendering;
          }
          else
          {
            str4 = fileById.Folder + fileById.FileName;
          }
        }
        else if (selectedValue == RenderingMethod.PredefinedXSL)
        {
          str = string.Format("~/DesktopModules/UserDefinedTable/XslStyleSheets/{0}", this.XslPreDefinedDropDownList.SelectedValue);
        }
        this.UpdateTabModuleSetting(SettingName.XslUserDefinedStyleSheet, str4);
        this.UpdateTabModuleSetting(SettingName.XslPreDefinedStyleSheet, str);
        this.UpdateTabModuleSetting(SettingName.RenderingMethod, selectedValue);
        this.UpdateTabModuleSetting(SettingName.Paging, this.cboPaging.SelectedValue);
        this.UpdateTabModuleSetting(SettingName.Filter, this.txtFilter.Text);

        if (string.IsNullOrEmpty(this.txtTopCount.Text))
          this.UpdateModuleSetting(SettingName.TopCount, string.Empty);

        else if (int.TryParse(this.txtTopCount.Text, out num3))
        {
          //int num3 = int.Parse(this.txtTopCount.Text);
          if (num3 < 1)
            num3 = 1;

          if (num3 > 0x3e8)
            num3 = 0x3e8;

          this.UpdateModuleSetting(SettingName.TopCount, num3.ToString());
        }

        this.UpdateTabModuleSetting(SettingName.TopCount, this.txtTopCount.Text);
        this.UpdateTabModuleSetting(SettingName.ShowSearchTextBox, this.chkShowSearchTextBox.Checked.ToString());
        this.UpdateTabModuleSetting(SettingName.ShowNoRecordsUntilSearch, this.chkShowNoRecordsUntilSearch.Checked.ToString());
        this.UpdateTabModuleSetting(SettingName.SimpleSearch, this.chkSimpleSearch.Checked.ToString());
        this.UpdateTabModuleSetting(SettingName.URLSearch, this.chkURLSearch.Checked.ToString());
        this.UpdateTabModuleSetting(SettingName.UseButtons, this.rblFormLinksOrButtons.SelectedValue);
        string str5 = selectedValue;

        if (str5 == RenderingMethod.GridRendering)

          this.UpdateTabModuleSetting(SettingName.UsedCssClasses, this.cboDnnCssClasses.SelectedValue);

        else if ((str5 == RenderingMethod.PredefinedXSL) || (str5 == RenderingMethod.UserdefinedXSL))
          this.UpdateTabModuleSetting(SettingName.UsedCssClasses, string.Empty);

        this.UpdateTabModuleSetting(SettingName.ListOrForm, this.rblUsageListForm.SelectedValue);
        this.UpdateTabModuleSetting(SettingName.ShowListRequiresPermission, (this.chkListViewPermission.Checked && this.rowListViewPermission.Visible).ToString());
        this.UpdateTabModuleSetting(SettingName.SubmissionText, HttpUtility.HtmlDecode(this.teSubmissionSuccess.Text));
        this.UpdateTabModuleSetting(SettingName.UponSubmitRedirect, this.urlOnSubmissionRedirect.Url);
        this.UpdateTabModuleSetting(SettingName.UponSubmitAction, this.rblOnSubmission.SelectedValue);
        this.UpdateTabModuleSetting(SettingName.TrackingEnabled, this.chkTracking.Checked.ToString());
        this.UpdateTabModuleSetting(SettingName.TableFreeEditForm, this.rblTableFreeForm.SelectedValue);
        string str3 = "";

        if (this.chkTracking.Checked)
        {
          if ((this.rblBodyType.SelectedValue == "XslScript") && !string.IsNullOrEmpty(this.XslTracking.Url))
          {
            DotNetNuke.Services.FileSystem.FileInfo info2 = new FileController().GetFileById(int.Parse(this.XslTracking.Url.Substring(7)), this.ModuleContext.PortalId);
            if (info2 != null)
              str3 = info2.Folder + info2.FileName;

          }
          else
            str3 = "[AUTO]";

        }
        this.UpdateTabModuleSetting(SettingName.TrackingScript, str3);
        this.UpdateTabModuleSetting(SettingName.TrackingEmailTo, this.txtTrackingEmailAddresses.Text);
        this.UpdateTabModuleSetting(SettingName.TrackingEmailCc, this.txtTrackingEmail_CC.Text);
        this.UpdateTabModuleSetting(SettingName.TrackingEmailBcc, this.txtTrackingEmail_BCC.Text);
        this.UpdateTabModuleSetting(SettingName.TrackingEmailReplyTo, this.txtTrackingEmail_replyto.Text);
        this.UpdateTabModuleSetting(SettingName.TrackingEmailFrom, this.txtTrackingEmail_from.Text);
        this.UpdateTabModuleSetting(SettingName.TrackingSubject, this.txtTrackingSubject.Text);
        this.UpdateTabModuleSetting(SettingName.TrackingMessage, HttpUtility.HtmlDecode(this.teTrackingMessage.Text));
        this.UpdateTabModuleSetting(SettingName.TrackingTriggerOnDelete, this.chkTrackingOnDelete.Checked.ToString());
        this.UpdateTabModuleSetting(SettingName.TrackingTriggerOnNew, this.chkTrackingOnNew.Checked.ToString());
        this.UpdateTabModuleSetting(SettingName.TrackingTriggerOnUpdate, this.chkTrackingOnUpdate.Checked.ToString());
        this.UpdateTabModuleSetting(SettingName.TrackingTextOnNew, this.txtOnNew.Text);
        this.UpdateTabModuleSetting(SettingName.TrackingTextOnUpdate, this.txtOnUpdate.Text);
        this.UpdateTabModuleSetting(SettingName.TrackingTextOnDelete, this.txtOnDelete.Text);
        this.SavePendingItem((sender));
      }
      catch (Exception e)
      {

        Exception exc = e;
        DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);

      }
    }





    private void SetHelpLinks()
    {
      string str = string.Format("javascript:OpenHelpWindow('{0}')", this.ResolveUrl("~/desktopmodules/userdefinedtable/HelpPopup.aspx?resourcekey=Help_Tokens"));
      this.hlpToken.NavigateUrl = str;
      this.hlpToken2.NavigateUrl = str;
      str = string.Format("javascript:OpenHelpWindow('{0}')", this.ResolveUrl("~/desktopmodules/userdefinedtable/HelpPopup.aspx?resourcekey=Help_HiddenColumns"));
      this.hlpColumns.NavigateUrl = str;
      this.hlpColumns2.NavigateUrl = str;
    }





    private bool TestForValidEmailSources(DataTable Fields, string EmailSources)
    {
      string str;

      foreach (string tmp in EmailSources.Split(new char[] { ';' }))
      {
        str = tmp.Trim();
        if (str.Length > 0)
        {
          if (str.StartsWith("[") && str.EndsWith("]"))
          {
            string str2 = str.Substring(1, str.Length - 2);
            DataRow[] rowArray = Fields.Select(string.Format("{0}='{1}'", FieldsTableColumn.Title, str2));
            if (rowArray.Length == 1)
            {
              if (!((DataType.ByName((string)rowArray[0][FieldsTableColumn.Type])) is IEmailAdressSource))
              {
                Skin.AddModuleMessage(this, string.Format(DotNetNuke.Services.Localization.Localization.GetString("NotEmailSource", this.LocalResourceFile), str2), ModuleMessage.ModuleMessageType.YellowWarning);
                return false;
              }
            }
            else if (rowArray.Length == 0)
            {
              Skin.AddModuleMessage(this, string.Format(DotNetNuke.Services.Localization.Localization.GetString("NotEmailSource", this.LocalResourceFile), str2), ModuleMessage.ModuleMessageType.YellowWarning);
              return false;
            }
          }
          else if (!DotNetNuke.Services.Mail.Mail.IsValidEmailAddress(str, this.ModuleContext.PortalId))
          {
            Skin.AddModuleMessage(this, string.Format(DotNetNuke.Services.Localization.Localization.GetString("NotEmailAddress", this.LocalResourceFile), str), ModuleMessage.ModuleMessageType.YellowWarning);
            return false;
          }
        }
      }
      return true;
    }





    private void UpdateModuleSetting(string Name, string value)
    {
      this.ModulesController.UpdateModuleSetting(this.ModuleContext.ModuleId, Name, value);
      this.ModuleContext.Settings[Name] = value;
    }





    private void UpdateTabModuleSetting(string Name, string value)
    {
      this.ModulesController.UpdateTabModuleSetting(this.ModuleContext.TabModuleId, Name, value);
      this.ModuleContext.Settings[Name] = value;
    }




    private bool ValidateMailTo()
    {
      StringBuilder builder = new StringBuilder();
      DataTable fieldsTable = this.UdtController.GetFieldsTable(false);
      return ((this.TestForValidEmailSources(fieldsTable, this.txtTrackingEmailAddresses.Text) && this.TestForValidEmailSources(fieldsTable, this.txtTrackingEmail_CC.Text)) && ((this.TestForValidEmailSources(fieldsTable, this.txtTrackingEmail_BCC.Text) && this.TestForValidEmailSources(fieldsTable, this.txtTrackingEmail_replyto.Text)) && this.TestForValidEmailSources(fieldsTable, this.txtTrackingEmail_from.Text)));
    }





    private int CurrentRow
    {
      get
      {
        if (this.ViewState["CurrentRow"] == null)
          return 0;

        return (int)this.ViewState["CurrentRow"];
      }
      set
      {
        this.ViewState["CurrentRow"] = value;
      }
    }




    private string CurrentTitle
    {
      get
      {
        if (this.ViewState["CurrentTitle"] == null)
          return "";

        return (string)this.ViewState["CurrentTitle"];
      }
      set
      {
        this.ViewState["CurrentTitle"] = value;
      }
    }




    private string CurrentType
    {
      get
      {
        if (this.ViewState["CurrentType"] == null)
          return "";

        return (string)this.ViewState["CurrentType"];
      }
      set
      {
        this.ViewState["CurrentType"] = value;
      }
    }




    ModuleActionCollection DotNetNuke.Entities.Modules.IActionable.ModuleActions
    {
      get
      {
        ModuleActionCollection actions = new ModuleActionCollection();
        string url = string.Format("javascript:{0}", this.Page.ClientScript.GetPostBackEventReference(this, "SaveSettingsAsDefault"));
        actions.Add(this.ModuleContext.GetNextActionID(), DotNetNuke.Services.Localization.Localization.GetString("SaveSettingsAsDefault.Action", this.LocalResourceFile), "", "", this.ResolveUrl("~/images/eip_save.gif"), url, false, SecurityAccessLevel.Edit, true, false);
        url = string.Format("javascript:if (confirm('{0}')) {1}", Utilities.CStrN(DotNetNuke.Services.Localization.Localization.GetString("ResetModuleTabSettings.Confirm", this.LocalResourceFile), "").Replace("'", @"\'"), this.Page.ClientScript.GetPostBackEventReference(this, "ResetModuleTabSettings"));
        actions.Add(this.ModuleContext.GetNextActionID(), DotNetNuke.Services.Localization.Localization.GetString("ResetModuleTabSettings.Action", this.LocalResourceFile), "", "", this.ResolveUrl("~/images/begin.gif"), url, false, SecurityAccessLevel.Edit, true, false);
        url = string.Format("javascript:if (confirm('{0}')) {1}", Utilities.CStrN(DotNetNuke.Services.Localization.Localization.GetString("DeleteAll.Confirm", this.LocalResourceFile), "").Replace("'", @"\'"), this.Page.ClientScript.GetPostBackEventReference(this, "DeleteAll"));
        actions.Add(this.ModuleContext.GetNextActionID(), DotNetNuke.Services.Localization.Localization.GetString("DeleteAll.Action", this.LocalResourceFile), "", "", this.ResolveUrl("~/images/delete.gif"), url, false, SecurityAccessLevel.Edit, true, false);
        return actions;
      }
    }




    public ModuleActionCollection ModuleActions
    {
      get
      {
        ModuleActionCollection actions = new ModuleActionCollection();
        string url = string.Format("javascript:{0}", this.Page.ClientScript.GetPostBackEventReference(this, "SaveSettingsAsDefault"));
        actions.Add(this.ModuleContext.GetNextActionID(), DotNetNuke.Services.Localization.Localization.GetString("SaveSettingsAsDefault.Action", this.LocalResourceFile), "", "", this.ResolveUrl("~/images/eip_save.gif"), url, false, SecurityAccessLevel.Edit, true, false);
        url = string.Format("javascript:if (confirm('{0}')) {1}", Utilities.CStrN(DotNetNuke.Services.Localization.Localization.GetString("ResetModuleTabSettings.Confirm", this.LocalResourceFile), "").Replace("'", @"\'"), this.Page.ClientScript.GetPostBackEventReference(this, "ResetModuleTabSettings"));
        actions.Add(this.ModuleContext.GetNextActionID(), DotNetNuke.Services.Localization.Localization.GetString("ResetModuleTabSettings.Action", this.LocalResourceFile), "", "", this.ResolveUrl("~/images/begin.gif"), url, false, SecurityAccessLevel.Edit, true, false);
        url = string.Format("javascript:if (confirm('{0}')) {1}", Utilities.CStrN(DotNetNuke.Services.Localization.Localization.GetString("DeleteAll.Confirm", this.LocalResourceFile), "").Replace("'", @"\'"), this.Page.ClientScript.GetPostBackEventReference(this, "DeleteAll"));
        actions.Add(this.ModuleContext.GetNextActionID(), DotNetNuke.Services.Localization.Localization.GetString("DeleteAll.Action", this.LocalResourceFile), "", "", this.ResolveUrl("~/images/delete.gif"), url, false, SecurityAccessLevel.Edit, true, false);
        return actions;
      }
    }

    public ModuleController ModulesController
    {
      get
      {
        if (this._objModules == null)
        {
          this._objModules = new ModuleController();
        }
        return this._objModules;
      }
    }





    private UserDefinedTableController UdtController
    {
      get
      {
        if (this._udtController == null)
        {
          this._udtController = new UserDefinedTableController(this.ModuleContext);
        }
        return this._udtController;
      }
    }





    #region databinding



    protected IDictionary<string, string> ContentDataTypes
    {
      get
      {
        return DataType.ContentDataTypes();
      }
    }




    protected IDictionary<string, string> SystemDataTypes
    {
      get
      {
        return DataType.SystemDataTypes();
      }
    }


    //protected object testMe(object dataItem)
    //{
    //  return dataTypeByName((string)((DataRowView)dataItem)[FieldsTableColumn.Type]).GetLocalization();
    //}





    protected DataType dataTypeByName(string name)
    {
      return DataType.ByName(name);
    }




    protected string getTypeName(string Name)
    {
      DataType type = DataType.ByName(Name);

      if (type.Name == Name)
        return type.GetLocalization("");

      Name = new PortalSecurity().InputFilter(Name, PortalSecurity.FilterFlag.NoMarkup);
      Skin.AddModuleMessage(this, string.Format(DotNetNuke.Services.Localization.Localization.GetString("DataTypeNotInstalled", this.LocalResourceFile), Name), ModuleMessage.ModuleMessageType.RedError);
      return string.Format("<img src=\"{1}/images/deny.gif\" alt=\"{0} not installed\" /> {0}", Name, DotNetNuke.Common.Globals.ApplicationPath);
    }




    protected bool isUserDefinedField(object dataItem)
    {
      return dataTypeByName((string)((DataRowView)dataItem)[FieldsTableColumn.Type]).IsUserDefinedField;
    }



    #endregion databinding


    private void loadFolders()
    {
      System.Web.HttpContext.Current.Trace.Write("enter Configuration.LoadFolders");


      this.cboDefaultFolder.Items.Clear();
      ListItem FolderItem;

      System.Web.HttpContext.Current.Trace.Write("Configuration.LoadFolders, scan folders...");

      //foreach (FolderInfo objFolder in FileSystemUtils.GetFoldersByUser(this.ModuleContext.PortalId, true, true, "READ, WRITE"))
      foreach (FolderInfo objFolder in FolderManager.Instance.GetFolders(this.ModuleContext.PortalSettings.UserInfo, "READ, WRITE"))
      {
        FolderItem = new ListItem();

        if ( string.IsNullOrEmpty(objFolder.FolderPath) )
        {
          FolderItem.Text = "/";
          FolderItem.Value = "";
        }
        else
        {
          FolderItem.Text = objFolder.FolderPath;
          FolderItem.Value = objFolder.FolderPath;
        }

        //FolderItem.Value = objFolder.FolderPath;

        this.cboDefaultFolder.Items.Add(FolderItem);
      }

      System.Web.HttpContext.Current.Trace.Write("Configuration.LoadFolders done");

    }


  }

}

